import { Card, Form, Input, Radio, DatePicker, Button, Tabs, Tree } from 'antd';
import React, { SetStateAction, useCallback, useEffect, useState } from 'react';
import styles from './index.less';
import { history } from 'umi';
import moment from 'moment';

import {
  tenantSave,
  tenantUpdate,
  tenantGetId,
  getByScope,
  getEntAdmin,
} from '@/services/clienteleControl';
import Const from '@/utils/Const';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { TabPane } = Tabs;

class PrivateData {
  static formLayout = {
    labelCol: {
      span: 24,
    },
    wrapperCol: {
      span: 24,
    },
  };
  static tabKey = '';
  static checkedKeysObj: any = {
    length: 0,
  };
  static testText = '测试通用2021062101 bf2.swcares.com';
  static dealSystemArr = (arr: any, id: string | number) => {
    let _arr = [];
    for (let item of arr) {
      let _item: any = {};
      _item.title = item.name;
      _item.key = item.id;
      if (item.flag) PrivateData.checkedKeysObj[+id].push(item.id);
      if (item.children && item.children.length !== 0) {
        _item.children = PrivateData.dealSystemArr(item.children, id);
      } else {
        _item.children = [];
      }
      _arr.push(_item);
    }
    return _arr;
  };
  static getCheckedKeysLength = () => {
    let _length = 0;
    let arr: any = [];
    for (let key in PrivateData.checkedKeysObj) {
      if (key === 'length') continue;
      PrivateData.checkedKeysObj[+key] = [
        ...new Set(PrivateData.checkedKeysObj[+key]),
      ];
      arr = [...arr, ...PrivateData.checkedKeysObj[+key]];
      _length += PrivateData.checkedKeysObj[+key].length;
    }
    PrivateData.checkedKeysObj.length = _length;
    return arr;
  };
}

const AddEditClientele: React.FC = (props: any) => {
  const {
    location: { state },
  } = props;
  const [form] = Form.useForm();
  const [tabPaneArr, setTabPaneArr] = useState<any[]>([]);
  const [treeData, setTreeData] = useState<any[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[] | number[]>([]);

  const getDepartmentTreeArr = useCallback(async () => {
    let res = await getByScope(state?.id ? [state?.id] : []);
    console.log(res, '--菜单资源树--');
    if (res && res.code === Const.successCode) {
      let arr = res.data || [];
      let _tabPane: any[] = [];
      for (let item of arr) {
        let _item: any = {};
        PrivateData.checkedKeysObj[+item.id] = [];
        _item.title = item.name;
        _item.key = item.id;
        _item.data = PrivateData.dealSystemArr(
          item.children || [],
          item.id || '',
        );
        _tabPane.push(_item);
      }
      PrivateData.tabKey = _tabPane[0]?.key || '';
      PrivateData.getCheckedKeysLength();
      setCheckedKeys(PrivateData.checkedKeysObj[+PrivateData.tabKey]);
      console.log(PrivateData.checkedKeysObj, 'PrivateData.checkedKeysObj');
      setTabPaneArr(_tabPane);
      setTreeData(_tabPane[0]?.data || []);
    }
  }, [state]);

  const getDetail = useCallback(async () => {
    let res = await tenantGetId(state.id);
    console.log(res, '--客户详情--');
    if (res.code === Const.successCode) {
      let data = res.data || '';
      let validDate: any[] = ['', ''];
      if (data.validFrom) validDate[0] = moment(data.validFrom);
      if (data.validTo) validDate[1] = moment(data.validTo);
      setTimeout(() => {
        form.setFieldsValue({
          name: data.name || '',
          status: data.status,
          domainName: data.domainName || '',
          companyName: data.companyName || '',
          contactor: data.contactor || '',
          contactorPhone: data.contactorPhone || '',
          contactorEmail: data.contactorEmail || '',
          userName: data.userName || '',
          validDate,
          comments: data.comments || '',
        });
      }, 0);
    }
    let userObj = await getEntAdmin(state.id);
    console.log(userObj, '获取管理员用户名');
    if (userObj && userObj.code && userObj.code === Const.successCode) {
      let data = userObj.data || {};
      setTimeout(() => {
        form.setFieldsValue({
          userName: data.name || '',
        });
      }, 0);
    }
  }, [state]);

  useEffect(() => {
    getDepartmentTreeArr();
    if (state.type !== 'add') {
      getDetail();
    }
    return () => {
      // if (form.resetFields) form.resetFields();
      PrivateData.tabKey = '';
      PrivateData.checkedKeysObj = {
        length: 0,
      };
    };
  }, [state]);

  // 返回
  const goBack = useCallback(() => {
    history.goBack();
  }, []);

  // 资源树选择
  const onCheck = useCallback((checkedKeys, info: any) => {
    console.log('onCheck', checkedKeys, info);
    setCheckedKeys(checkedKeys);
    PrivateData.checkedKeysObj[+PrivateData.tabKey] = [...checkedKeys];
  }, []);

  // tab切换
  const tabChange = useCallback(
    (key) => {
      if (+PrivateData.tabKey === +key) return;
      console.log(key, PrivateData.checkedKeysObj, '--key--');
      PrivateData.tabKey = key;
      for (let item of tabPaneArr) {
        if (+item.key === +key) {
          setTreeData(item.data);
          setCheckedKeys(PrivateData.checkedKeysObj[+PrivateData.tabKey]);
          break;
        }
      }
    },
    [tabPaneArr],
  );

  // 确认
  const onFinish = useCallback(() => {
    form.validateFields().then((values) => {
      let checkedKeysLength = PrivateData.getCheckedKeysLength();
      if (checkedKeysLength.length !== 0) {
        if (values.validDate && values.validDate[0].isValid()) {
          values.validFrom = moment(values.validDate[0]).valueOf();
          values.validTo = moment(values.validDate[1]).valueOf();
          delete values.validDate;
        }
        console.log(values, '--values--');
        if (state.type === 'add') {
          tenantSave({
            ...values,
            resourceList: checkedKeysLength,
          }).then((res) => {
            console.log(res, '新增客户');
            if (Const.successCode === res.code) {
              goBack();
            }
          });
        }
        if (state.type === 'edit') {
          tenantUpdate({
            ...values,
            id: state.id || '',
            resourceList: checkedKeysLength,
          }).then((res) => {
            console.log(res, '编辑客户');
            if (Const.successCode === res.code) {
              goBack();
            }
          });
        }
      }
    });
  }, [state]);

  return (
    <>
      <div className={styles.addEditClientele}>
        <Card title={'基本信息'} style={{ width: '100%' }}>
          <Form
            {...PrivateData.formLayout}
            layout="vertical"
            className={styles.formContent}
            form={form}
          >
            <FormItem
              label="客户名称"
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入客户名称',
                },
              ]}
            >
              <Input
                disabled={state?.type === 'view'}
                placeholder="请输入客户名称"
                maxLength={16}
              />
            </FormItem>
            <FormItem
              label="客户状态"
              name="status"
              rules={[
                {
                  required: true,
                  message: '请选择客户状态',
                },
              ]}
            >
              <Radio.Group disabled={state?.type === 'view'}>
                <Radio value={1}>启用</Radio>
                <Radio value={0}>停用</Radio>
              </Radio.Group>
            </FormItem>
            <FormItem
              label="客户域名"
              name="domainName"
              rules={[
                {
                  required: true,
                  message: '请输入客户域名',
                },
              ]}
            >
              <Input
                disabled={state?.type === 'view'}
                placeholder="请输入客户域名"
                maxLength={255}
              />
            </FormItem>
            <FormItem
              label="公司全称"
              name="companyName"
              rules={[
                {
                  required: true,
                  message: '请输入公司全称',
                },
              ]}
            >
              <Input
                disabled={state?.type === 'view'}
                placeholder="请输入公司全称"
                maxLength={255}
              />
            </FormItem>
            <FormItem
              label="联系人"
              name="contactor"
              rules={[
                {
                  required: true,
                  message: '请输入联系人',
                },
              ]}
            >
              <Input
                disabled={state?.type === 'view'}
                placeholder="请输入联系人"
                maxLength={16}
              />
            </FormItem>
            <FormItem
              label="联系电话"
              name="contactorPhone"
              rules={[
                {
                  required: true,
                  message: '请输入联系电话',
                },
                {
                  pattern: /(^1[3|4|5|8]\d{9}$)|(^\d{3}-\d{8}$)/,
                  message: '请输入正确格式',
                },
              ]}
            >
              <Input
                maxLength={13}
                disabled={state?.type === 'view'}
                placeholder="请输入联系电话"
              />
            </FormItem>
            <FormItem
              label="联系邮箱"
              name="contactorEmail"
              rules={[
                {
                  required: true,
                  message: '请输入联系邮箱',
                },
              ]}
            >
              <Input
                disabled={state?.type === 'view'}
                placeholder="请输入联系邮箱"
                maxLength={32}
              />
            </FormItem>
            <FormItem
              label="管理员用户名"
              name="userName"
              rules={[
                {
                  required: true,
                  message: '请输入管理员用户名',
                },
              ]}
            >
              <Input
                disabled={state?.type === 'view'}
                placeholder="请输入管理员用户名"
                maxLength={16}
              />
            </FormItem>
            <FormItem
              label="选择日期"
              name="validDate"
              rules={[
                {
                  required: true,
                  message: '请选择日期',
                },
              ]}
            >
              <RangePicker
                style={{ width: '100%' }}
                format={Const.format}
                disabled={state?.type === 'view'}
              ></RangePicker>
            </FormItem>
            <FormItem
              label="备注"
              name="comments"
              style={{ width: '100%', flex: '0 0 100%' }}
            >
              <TextArea
                placeholder="请输入备注"
                autoSize={{ minRows: 4, maxRows: 4 }}
                disabled={state?.type === 'view'}
                maxLength={200}
                showCount
              />
            </FormItem>
          </Form>
        </Card>
        <Card title={'系统配置'}>
          <Tabs onChange={tabChange}>
            {tabPaneArr.map((item) => (
              <TabPane key={item.key} tab={item.title}>
                <Card title={item.title}>
                  <Tree
                    checkable
                    onCheck={onCheck}
                    selectable={false}
                    treeData={treeData}
                    checkedKeys={checkedKeys}
                    disabled={state.type === 'view'}
                  />
                </Card>
              </TabPane>
            ))}
          </Tabs>
        </Card>
        <div className={styles.btnBox}>
          <Button style={{ marginRight: '20px' }} onClick={goBack}>
            取 消
          </Button>
          <Button
            type="primary"
            onClick={onFinish}
            disabled={state?.type === 'view'}
          >
            确 认
          </Button>
        </div>
      </div>
    </>
  );
};

export default AddEditClientele;
